package com.henghai.zhenxuan.ui.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.henghai.zhenxuan.data.bean.LogisticsItem;
import com.henghai.zhenxuan.R;

import java.util.ArrayList;
import java.util.List;

public class LogisticsTrackView extends LinearLayout {
    private int lineColor = Color.parseColor("#E0E0E0");
    private int pointColor = Color.parseColor("#4CAF50");
    private int currentPointColor = Color.parseColor("#FF5722");
    private int firstPointColor = Color.parseColor("#4CAF50"); // 第一个圆点颜色
    private int lastPointColor = Color.parseColor("#9E9E9E");  // 最后一个圆点颜色
    private int textColor = Color.parseColor("#333333");
    private int timeTextColor = Color.parseColor("#999999");

    // 圆点大小控制
    private int normalPointRadius = dpToPx(6);
    private int firstPointRadius = dpToPx(8);  // 第一个圆点更大
    private int lastPointRadius = dpToPx(6);   // 最后一个圆点大小

    // 是否使用特殊样式
    private boolean useSpecialFirstPoint = true;
    private boolean useSpecialLastPoint = true;

    // 折叠展开相关属性
    private boolean isExpanded = false;
    private int collapsedItemCount = 3; // 折叠时显示的条目数量
    private TextView expandCollapseButton;
    private OnExpandStateChangeListener expandStateChangeListener;

    private List<LogisticsItem> items = new ArrayList<>();
    private Paint linePaint;
    private Paint pointPaint;

    public LogisticsTrackView(Context context) {
        super(context);
        init();
    }

    public LogisticsTrackView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public LogisticsTrackView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setOrientation(VERTICAL);
        setWillNotDraw(false); // 允许自定义绘制

        // 初始化线条画笔
        linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        linePaint.setColor(lineColor);
        linePaint.setStrokeWidth(dpToPx(2));

        // 初始化圆点画笔
        pointPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        pointPaint.setStyle(Paint.Style.FILL);
    }

    public void setItems(List<LogisticsItem> items) {
        this.items = items;
        updateView();
    }

    // 设置折叠时显示的条目数量
    public void setCollapsedItemCount(int count) {
        this.collapsedItemCount = count;
        updateView();
    }

    // 获取当前是否展开
    public boolean isExpanded() {
        return isExpanded;
    }

    // 设置展开/折叠状态
    public void setExpanded(boolean expanded) {
        if (this.isExpanded != expanded) {
            this.isExpanded = expanded;
            updateView();

            if (expandStateChangeListener != null) {
                expandStateChangeListener.onExpandStateChanged(expanded);
            }
        }
    }

    // 切换展开/折叠状态
    public void toggleExpanded() {
        setExpanded(!isExpanded);
    }

    // 设置展开状态变化监听器
    public void setOnExpandStateChangeListener(OnExpandStateChangeListener listener) {
        this.expandStateChangeListener = listener;
    }

    public void setLineColor(int color) {
        this.lineColor = color;
        linePaint.setColor(color);
        invalidate();
    }

    public void setPointColor(int color) {
        this.pointColor = color;
        invalidate();
    }

    public void setCurrentPointColor(int color) {
        this.currentPointColor = color;
        invalidate();
    }

    // 设置第一个圆点颜色
    public void setFirstPointColor(int color) {
        this.firstPointColor = color;
        invalidate();
    }

    // 设置最后一个圆点颜色
    public void setLastPointColor(int color) {
        this.lastPointColor = color;
        invalidate();
    }

    // 设置第一个圆点半径
    public void setFirstPointRadius(int radiusDp) {
        this.firstPointRadius = dpToPx(radiusDp);
        invalidate();
    }

    // 设置最后一个圆点半径
    public void setLastPointRadius(int radiusDp) {
        this.lastPointRadius = dpToPx(radiusDp);
        invalidate();
    }

    // 设置普通圆点半径
    public void setNormalPointRadius(int radiusDp) {
        this.normalPointRadius = dpToPx(radiusDp);
        invalidate();
    }

    // 是否使用特殊第一个圆点样式
    public void setUseSpecialFirstPoint(boolean use) {
        this.useSpecialFirstPoint = use;
        invalidate();
    }

    // 是否使用特殊最后一个圆点样式
    public void setUseSpecialLastPoint(boolean use) {
        this.useSpecialLastPoint = use;
        invalidate();
    }

    public void setTextColor(int color) {
        this.textColor = color;
        updateView();
    }

    public void setTimeTextColor(int color) {
        this.timeTextColor = color;
        updateView();
    }

    private void updateView() {
        removeAllViews();

        if (items == null || items.isEmpty()) {
            return;
        }

        LayoutInflater inflater = LayoutInflater.from(getContext());
        int displayCount = isExpanded ? items.size() : Math.min(items.size(), collapsedItemCount);

        // 添加物流条目
        for (int i = 0; i < displayCount; i++) {
            LogisticsItem item = items.get(i);

            // 创建每个物流节点视图
            View itemView = inflater.inflate(com.henghai.zhenxuan.R.layout.logistics_item, this, false);
            TextView statusText = itemView.findViewById(R.id.status_text);
            TextView timeText = itemView.findViewById(R.id.time_text);

            // 设置内容
            statusText.setText(item.getStatus());
            statusText.setTextColor(textColor);
            timeText.setText(item.getTime());
            timeText.setTextColor(timeTextColor);

            addView(itemView);
        }

        // 如果需要显示展开/折叠按钮
        if (items.size() > collapsedItemCount) {
            addExpandCollapseButton(inflater);
        }

        // 请求重新绘制连接线和圆点
        postInvalidate();
    }

    private void addExpandCollapseButton(LayoutInflater inflater) {
        View buttonView = inflater.inflate(R.layout.logistics_expand_button, this, false);
        expandCollapseButton = buttonView.findViewById(R.id.expand_collapse_button);

        if (isExpanded) {
            expandCollapseButton.setText("收起");
        } else {
            expandCollapseButton.setText("展开更多(" + (items.size() - collapsedItemCount) + ")");
        }

        expandCollapseButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleExpanded();
            }
        });

        addView(buttonView);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (getChildCount() == 0) {
            return;
        }

        // 计算连接线的X坐标
        int lineX = dpToPx(24); // 圆点距离左侧边框的距离

        // 计算第一个和最后一个圆点的Y坐标
        int firstPointY = -1;
        int lastPointY = -1;
        int visibleItemCount = 0;

        // 先计算所有可见物流条目的位置
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);

            // 跳过展开/折叠按钮
            if (child.getId() == R.id.expand_collapse_container) {
                continue;
            }

            // 获取状态文本视图
            TextView statusText = child.findViewById(R.id.status_text);

            // 使用全局位置计算文字组件顶部
            int[] location = new int[2];
            statusText.getLocationOnScreen(location);
            int textTop = location[1];

            // 转换为相对于当前视图的坐标
            int[] myLocation = new int[2];
            this.getLocationOnScreen(myLocation);
            textTop -= myLocation[1];

            // 圆点顶部与文字组件顶部对齐
            int pointCenterY = textTop + dpToPx(6);

            // 记录第一个和最后一个圆点的Y坐标
            if (firstPointY == -1) {
                firstPointY = pointCenterY;
            }
            lastPointY = pointCenterY;

            visibleItemCount++;
        }

        // 只有在有可见物流条目时才绘制连接线
        if (visibleItemCount > 0 && firstPointY != -1 && lastPointY != -1) {
            canvas.drawLine(lineX, firstPointY, lineX, lastPointY, linePaint);
        }

        // 然后绘制圆点（确保圆点在连接线上方）
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);

            // 跳过展开/折叠按钮
            if (child.getId() == R.id.expand_collapse_container) {
                continue;
            }

            // 获取状态文本视图
            TextView statusText = child.findViewById(R.id.status_text);

            // 使用全局位置计算文字组件顶部
            int[] location = new int[2];
            statusText.getLocationOnScreen(location);
            int textTop = location[1];

            // 转换为相对于当前视图的坐标
            int[] myLocation = new int[2];
            this.getLocationOnScreen(myLocation);
            textTop -= myLocation[1];

            // 圆点顶部与文字组件顶部对齐
            int pointCenterY = textTop + dpToPx(6);

            // 设置圆点颜色和大小
            int pointRadius;
            int itemIndex = getItemIndexForView(i);

            if (itemIndex == 0 && useSpecialFirstPoint) {
                // 第一个圆点
                pointPaint.setColor(firstPointColor);
                pointRadius = firstPointRadius;
            } else if (itemIndex == items.size() - 1 && useSpecialLastPoint) {
                // 最后一个圆点
                pointPaint.setColor(lastPointColor);
                pointRadius = lastPointRadius;
            } else {
                // 普通圆点
                if (items.get(itemIndex).isCurrent()) {
                    pointPaint.setColor(currentPointColor);
                } else {
                    pointPaint.setColor(pointColor);
                }
                pointRadius = normalPointRadius;
            }

            // 绘制圆点
            canvas.drawCircle(lineX, pointCenterY, pointRadius, pointPaint);
        }
    }

    // 辅助方法：根据视图索引获取对应的数据项索引
    private int getItemIndexForView(int viewIndex) {
        int itemIndex = viewIndex;
        // 如果视图索引超过了实际数据项数量（因为有展开/折叠按钮），则返回最后一个数据项
        if (itemIndex >= items.size()) {
            itemIndex = items.size() - 1;
        }
        return itemIndex;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 确保在测量后重新绘制
        postInvalidate();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        // 确保在布局后重新绘制
        postInvalidate();
    }

    private int dpToPx(float dp) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return Math.round(dp * density);
    }

    // 展开状态变化监听器接口
    public interface OnExpandStateChangeListener {
        void onExpandStateChanged(boolean isExpanded);
    }
}